const portfinder = require('portfinder');
const { merge } = require('webpack-merge');
const { resolve, getIPAddress } = require('./utils');
const baseWebpackConfig = require('./webpack_base');
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');

const port = 9010

const devWebpackConfig = merge(baseWebpackConfig, {
    mode: 'development',
    devtool: 'cheap-module-eval-source-map', // 没有列映射的SourceMap忽略加载程序源映射
    devServer: {
        port: port,
        host: '0.0.0.0', // 局域网可访问
        hot: true, // 热更新
        open: false, // 自动打开浏览器
        hotOnly: true, // 当热编译失败时，不刷新页面
        noInfo: true, // 隐藏打包明细，只显示 Errors 和 warnings
        contentBase: resolve('dist'),
        compress: true, // 启用gzip压缩
        progress: true, // 进度条
        inline: true // 自动刷新
    },
    plugins: []
});


module.exports = new Promise((resolve, reject) => {
    // 异步获取可用端口
    portfinder.basePort = port
    portfinder.getPort((err, newport) => {
        if (err) {
            reject(err)
        } else {
            devWebpackConfig.devServer.port = newport
            devWebpackConfig.devServer.openPage = `http://localhost:${newport}/`
            devWebpackConfig.plugins.push(// 错误友好提示
                new FriendlyErrorsPlugin({
                    compilationSuccessInfo: {
                        messages: [
                            `- Local:     http://localhost:${newport}`,
                            `- Network:   http://${getIPAddress()}:${newport}`
                        ],
                    },
                    onErrors: function (severity, errors) { }
                }))
            resolve(devWebpackConfig)
        }
    })
})